package com.cms.controllers.admin;

import com.cms.common.aop.permission.PermissionCheck;
import com.cms.common.model.entity.Language;
import com.cms.common.model.services.LanguageService;
import com.cms.common.model.vo.ResponseResult;
import com.cms.controllers.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/admin/language")
public class LanguageController extends BaseController {

    @Autowired
    private LanguageService languageService;

    @GetMapping("")
    @PermissionCheck(name = "语言列表界面", typeName = "语言管理")
    public String index(Model model) {
        return "admin/language/index";
    }

    @GetMapping("/list")
    @ResponseBody
    @PermissionCheck(name = "语言列表", typeName = "语言管理")
    public ResponseResult list() {
        return ResponseResult.success(languageService.findAll());
    }

    @PostMapping("/save")
    @ResponseBody
    @PermissionCheck(name = "保存语言", typeName = "语言管理")
    public ResponseResult save(@RequestParam("code") String code, @RequestParam("name") String name, @RequestParam("isDefault") boolean isDefault, @RequestParam("enabled") boolean enabled) {
        try {
            Language language = languageService.findByCode(code);
            language = language == null ? new Language() : language;
            language.setCode(code);
            language.setName(name);
            language.setIsDefault(isDefault);
            language.setEnabled(enabled);
            languageService.save(language);
            return ResponseResult.success("保存成功");
        } catch (Exception e) {
            return ResponseResult.fail("保存失败：" + e.getMessage());
        }
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    @PermissionCheck(name = "删除语言", typeName = "语言管理")
    public ResponseResult delete(@PathVariable Long id) {
        try {
            languageService.delete(id);
            return ResponseResult.success("删除成功");
        } catch (Exception e) {
            return ResponseResult.fail("删除失败：" + e.getMessage());
        }
    }
}
